//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using OpenLS.Core.Serialization;
using OpenLS.Spreadsheet.Office2003;

namespace OpenLS.Spreadsheet.Formats
{
    public class Office2003XmlSpreadsheetFormat : SpreadsheetFormat
    {
        public override SpreadsheetDocument Open(Stream xmlStream)
        {
            using (XmlReader reader = new XmlTextReader(xmlStream))
            {
                using (ReadContext ctx = new ReadContext(reader, null, XmlSpreadsheetConstants.XmlSpreadsheetNamespaceUri))
                {
                    ExpandedRange r = new ExpandedRange();
                    ctx.AddData<ExpandedRange>(r);
                    ctx.AddData<StyleLookup>(new StyleLookup());
                    SpreadsheetDocument result = SpreadsheetDocument.CreateEmpty(SpreadsheetContext.Default);//\\ new SpreadsheetDocument(SpreadsheetContext.Default); //\\
                    IOffice2003XmlSerializable w = result.Workbook;
                    result.Workbook.UndoEnabled = false;
                    w.ReadXmlSpreadsheet(ctx);
                    if (result.Workbook.Sheets.Count > 0)
                    {
                        Worksheet ws = result.Workbook.Sheets[result.Workbook.Sheets.Count - 1] as Worksheet;
                        ws.Selection = ws.GetRange(new RangeAddress(new CellAddress(0, 0), new CellAddress(r.ExpandedRowCount - 1, r.ExpandedColumnCount - 1)));
                    }
                    return result;
                }
            }
        }

        public override void Save(SpreadsheetDocument document, Stream stream)
        {
            throw new NotImplementedException();
        }

        public override string ClipboardName
        {
            get { return SpreadsheetDataFormats.XmlSpreadsheetFormat; }
        }

        public override IEnumerable<string> Extensions
        {
            get { yield return "xml"; }
        }
    }
}
